package servlet.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.ArticleImgModel;
import model.TPhoto;
import model.VBackAdminUser;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import persistent.dao.PhotoDAO;
import persistent.factory.DAOFactory;

import com.alibaba.fastjson.JSON;

import util.toolkit.Constant;
import util.toolkit.ResponseJSON;

/**
 * 处理来自jsp上传文件的控制类 1、接受上传文件 2、创建文件在服务器上的存储路径 3、保存文件在路径中
 * 
 * @since 2019-04-03
 */
public class ArticleImgUploadServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		// 定义一个用于返回值的json类型对象
		JSONObject result = new JSONObject();
		//定义返回值对象
		ArticleImgModel articleImg = new ArticleImgModel();

		String fileName = null; // 上传到Servlet的文件名
		request.setCharacterEncoding("utf-8");
		response.setContentType("application/json");

		// 存放文件的相对路径，博主照片一般存放在relaPath代表路径中
		// 因此relaPath通常接受的参数是博主的userid
		VBackAdminUser adminuser = (VBackAdminUser) request.getSession().getAttribute("backUser");
		String relaPath = adminuser.getUserid().trim();

		// 如果网页还有其它参数，则以下的循环将把其它参数一并的取出来
		Enumeration em = request.getParameterNames();
		while (em.hasMoreElements()) {
			String s = (String) em.nextElement();
		}

		ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());// 解析
																					// //创建上传文件对象
		try {
			// itemList保存有从jsp中获取出来的图片的全路径名称
			List itemList = upload.parseRequest(request); // 从请求对象中获得对象列表
			for (Iterator it = itemList.iterator(); it.hasNext();) {
				FileItem item = (FileItem) it.next();
				if (!item.isFormField())// 如果是非表单数据
				{
					if (item.getName().length() <= 0)
						return;// 表示后面的文件域没有选中文件

					// 方式二：采用文件输入输出流，输出文件
					// 统一Linux与windows的路径分隔符
					fileName = item.getName().replace("/", "\\");

					if (fileName.lastIndexOf("\\") != -1) { // 如果取到的文件地址拥有目录路径，则将目录路径去除
						fileName = fileName.substring(fileName.lastIndexOf("\\"));
					}

					//
					String path = ""; // 项目在服务器上的路径
					if (relaPath == null || relaPath.equals("")) {
						path = Constant.SERVERPATH + "\\article\\img\\";
					} else {
						path = Constant.SERVERPATH + "\\article\\img\\" + relaPath + "\\";
					}
					System.out.println(path);
					File f = new File(path, fileName);
					f.getParentFile().mkdirs();// 保证路径存在

					InputStream ins = item.getInputStream();
					OutputStream ous = new FileOutputStream(f);
					byte[] tmp = new byte[1024];
					int len = -1;

					// 从上传对象中读取数据，并写入 到创建的服务器文件中
					while ((len = ins.read(tmp)) != -1) {
						ous.write(tmp, 0, len);
					}
					ous.close();
					ins.close();

					// 图片资源上传成功后，将在T_Photo表中创建一条图片资源的管理记录
					PhotoDAO pdao = DAOFactory.getPhotoDAO();
					TPhoto photo = new TPhoto();
					photo.setPath(relaPath + "\\\\" + fileName);
					photo.setStatus("true");
					int photoid = pdao.addPhoto(photo);
					
					articleImg.setSrc(".."+Constant.FICTITIOUSPATH + "article/img/" + relaPath + "/" + fileName);
					articleImg.setTitle(fileName);
					
					String src = Constant.FICTITIOUSPATH + "article/img/" + relaPath + "/" + fileName;
					
					
					String data = "{\"src\":" + "\"" + src + "\"" + ",\"title\":" + "\"" + fileName + "\"" + "}";
					
					result.put("code", 0);
					result.put("msg", "图片上传成功");
					//JSONArray jsonArray = JSONArray.fromObject(articleImg);
					result.put("data", data);
					
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("code", 1);
			result.put("msg", "图片上传失败");
		}

		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json");
		PrintWriter out = response.getWriter();
		System.out.println(JSON.toJSONString(result));
		out.write(JSON.toJSONString(result));
	}

	public String getRootPath(String path) {
		String rootpath;
		int pos = path.lastIndexOf("\\");
		rootpath = path.substring(0, pos);
		pos = rootpath.lastIndexOf("\\");
		rootpath = rootpath.substring(0, pos + 1);
		return rootpath;
	}
}
